<template>
  <a-affix :offset-top="55">
    <div class="blog_toc_header">
      目录
    </div>
    <div id="blog_toc"></div>
  </a-affix>
</template>

<script>
import { defineComponent, nextTick, onMounted, reactive } from 'vue'

export default defineComponent({
  setup () {
    const state = reactive({
      anchorClass: 'blog-anchor',
      tocContainerId: 'markdown_it_toc',
      tocDomId: 'blog_toc'
    })

    onMounted(() => {
      nextTick(() => {
        // 生成目录
        // 清空之前的目录
        const tocDom = document.getElementById(state.tocDomId)
        tocDom.innerHTML = ''
        // 解决锚点问题
        const dom = document.getElementsByClassName(state.anchorClass)
        dom.forEach((item) => {
          item.onclick = (event) => {
            event.preventDefault()
            const split = event.target.href.split('#')
            const domId = split[split.length - 1]
            document.documentElement.scrollTop = document.getElementById(domId).offsetTop
          }
        })
        // 解决目录问题
        const markdownItToc = document.getElementById(state.tocContainerId)
        // 如果没有目录不执行后方代码
        if (markdownItToc === null) {
          return
        }
        // 设置目录样式
        markdownItToc.style.marginLeft = '20px'
        tocDom.append(markdownItToc)
        markdownItToc.querySelectorAll('ul').forEach((item) => {
          item.style.marginLeft = '-25px'
        })
        markdownItToc.querySelectorAll('a').forEach((item) => {
          item.style.color = '#00000090'
        })
      })
    })
  }
})
</script>

<style lang="less" scoped>
.blog_toc_header {
  margin-top: 20px;
  font-size: 18px;
  font-weight: 700;
  padding-bottom: 10px;
  display: flex;
  justify-content: center;
}

.blog_toc_content {
  margin-top: 20px;
  font-size: 18px;
  font-weight: 700;
  padding-bottom: 10px;
}
</style>
